#include "SList.h"

void print(SLTNode* phead)
{
	SLTNode* tail = phead;
	while (tail != NULL)
	{
		printf("%d ", tail->data);
		tail = tail->next;
	}
	printf("\n");
}

void SLTNodePushBack(SLTNode** phead, SLTDateType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	newnode->data = x;
	newnode->next = NULL;
	if (*phead == NULL)
	{
		*phead = newnode;
	}
	else
	{
		SLTNode* tail = *phead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SLTNodePushFront(SLTNode** phead, SLTDateType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	newnode->data = x;
	newnode->next = *phead;
	*phead = newnode;
}

void SLTNodePopFront(SLTNode** phead)
{
	SLTNode* tmp = (*phead)->next;
	free(*phead);
	*phead = tmp;
}


void SLTNodePopBack(SLTNode** phead)
{
	if (*phead == NULL)
	{
		return;
	}
	else if ((*phead)->next == NULL)
	{
		free(*phead);
		*phead = NULL;
	}
	else
	{
		SLTNode* prv = NULL;
		SLTNode* tail = *phead;
		while (tail->next != NULL)
		{
			prv = tail;
			tail = tail->next;
		}
		free(tail);
		prv->next= NULL;
	}
}


SLTNode* SListFind(SLTNode* phead, SLTDateType x)
{
	SLTNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;

}
void SListInsert(SLTNode** phead, SLTNode* pos, SLTDateType x)
{
	if (pos == *phead)
	{
		SLTNodePushFront(phead,x);
	}
	else
	{
		SLTNode* newnode= CreateNode(x);
		SLTNode* prev = *phead;
		while (prev->next!=pos)
		{
			prev = prev->next;
		}
		newnode ->next= pos;
		prev->next = newnode;

	}
}
void SListErase(SLTNode** phead, SLTNode* pos)
{
	if (pos == *phead)
	{
		SLTNodePopFront(phead);
	}
	else
	{
		SLTNode* prev = *phead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}

SLTNode* CreateNode(SLTDateType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	newnode->data = x;
	newnode->next = NULL;
	return newnode;

}